package ldh.im.fxgui.rpc.service;

import ldh.im.ImConfig;
import ldh.im.fxbase.dao.ImGroupDao;
import ldh.im.fxbase.dao.ImGroupUserDao;
import ldh.im.fxbase.dao.ImSessionDao;
import ldh.im.fxbase.data.event.EventBusFactory;
import ldh.im.fxbase.data.event.GroupUserNameChange;
import ldh.im.fxbase.data.event.SessionChange;
import ldh.im.fxbase.data.pojo.ImGroup;
import ldh.im.fxbase.data.pojo.ImGroupUser;
import ldh.im.fxbase.data.pojo.ImSession;
import ldh.im.fxbase.util.BeanFactory;

import java.sql.SQLException;
import java.util.Date;
import java.util.Set;

public class GroupUserChangeDataService {

    private ImGroupUserDao groupUserDao = BeanFactory.getInstance().getBean(ImGroupUserDao.class);
    private ImGroupDao groupDao = BeanFactory.getInstance().getBean(ImGroupDao.class);
    private ImSessionDao sessionDao = BeanFactory.getInstance().getBean(ImSessionDao.class);

    // 修改群聊中用户名称
    public void editGroupUserName(String userId, String key, String userName) throws SQLException {
        int index = key.lastIndexOf(ImConfig.MESSAGE_SPLIT);
        String groupId = key.substring(0, index);
        String guUserId = key.substring(index + ImConfig.MESSAGE_SPLIT.length());
        ImGroup imGroup = groupDao.getByUserIdAndId(userId, groupId);
        Set<ImGroupUser> groupUsers = imGroup.getGroupUserSet();
        ImGroupUser groupUser = groupUsers.stream().filter(gu->gu.getUserId().equals(guUserId)).findFirst().get();

        groupUser.setUserName(userName);
        groupUser.setUpdateTime(new Date());
        groupUserDao.update(groupUser);

        ImSession session = sessionDao.getByGroupCodeAndUserId(groupId, userId);

        EventBusFactory.getInstance().post(new GroupUserNameChange(session.getId(), guUserId, userName));
    }

    // 修改群聊中是否展示用户名
    public void editGroupShowName(String userId, String key, String isShowNameStr) throws SQLException {
        int index = key.lastIndexOf(ImConfig.MESSAGE_SPLIT);
        String groupId = key.substring(0, index);
        String guUserId = key.substring(index + ImConfig.MESSAGE_SPLIT.length());

        ImGroup imGroup = groupDao.getByUserIdAndId(userId, groupId);
        Set<ImGroupUser> groupUsers = imGroup.getGroupUserSet();
        ImGroupUser groupUser = groupUsers.stream().filter(gu->gu.getUserId().equals(guUserId)).findFirst().get();

        boolean isShowName = Boolean.parseBoolean(isShowNameStr);
        groupUser.setShowName(isShowName);
        groupUser.setUpdateTime(new Date());
        groupUserDao.update(groupUser);

        ImSession session = sessionDao.getByGroupCodeAndUserId(groupId, userId);

        EventBusFactory.getInstance().post(new SessionChange(session.getId()));
    }
}
